package com.jiesen.base.modules.company.controller;

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.jiesen.base.modules.company.model.JsPublicUsersGroupby;
import com.jiesen.base.modules.company.service.JsPublicUsersGroupbyService;
import com.jiesen.base.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiesen.base.baseDao.RedisServiceImpl;
import com.jiesen.base.modules.company.model.JsPublicUsers;
import com.jiesen.base.modules.company.model.JsPublicUsersRecord;
import com.jiesen.base.modules.company.service.IJsPublicUsersRecordService;
import com.jiesen.base.modules.company.service.IJsPublicUsersService;
import com.jiesen.base.modules.login.jsLoginUser.model.JsLoginUser;
import com.jiesen.base.modules.login.jsRole.model.JsRole;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 公海认领记录表 前端控制器
 * </p>
 *
 * @author bao
 */

@RestController
@RequestMapping(value = "/jsPublicUsersRecord", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class JsPublicUsersRecordController {

    @Autowired
    private IJsPublicUsersRecordService jsPublicUsersRecordService;

    @Autowired
    private IJsPublicUsersService jsPublicUsersService;

    @Autowired
    private JsPublicUsersGroupbyService jsPublicUsersGroupbyService;

    @Autowired
    JWTUtil jwtUtil;

    @Autowired
    private RedisServiceImpl redisService;

    //根据条件查询当前用户所拥有的公海用户的数据
    @RequestMapping("/getList")
    @ResponseBody
    public R getList(JsPublicUsersRecord jsPublicUsersRecord) {
        String token = jwtUtil.getSystemToken();
        String userId = JWTUtil.getUserId(token);
        jsPublicUsersRecord.setUserId(Integer.parseInt(userId));
        jsPublicUsersRecord.setState(1);
        //ArrayList<JsPublicUsers> arrayList = new ArrayList<JsPublicUsers>();
        List<JsPublicUsersRecord> list = jsPublicUsersRecordService.list1(jsPublicUsersRecord);
        if (list.size() == 0) {
            return R.ok("没有数据");
        }
        List<Integer> ids = new ArrayList<>();
        for (JsPublicUsersRecord jsPublicUsersRecord2 : list) {

            ids.add(jsPublicUsersRecord2.getPublicUsersId());

            //JsPublicUsers publicUsers = jsPublicUsersService.getById(jsPublicUsersRecord2.getPublicUsersId());
            //arrayList.add(publicUsers);
        }
        List<JsPublicUsers> list1 = jsPublicUsersService.list(ids);
        return R.ok().put("data", list1);
    }

    /**
     * 领取我的客户 一次增加20个
     *
     * @Description
     * @author bao
     * @data Aug 27, 2020 5:02:35 PM
     */
    //@RequestMapping("/addPublicUsersRecord")
    //@ResponseBody
    /*public R addPublicUsersRecord(@RequestParam(value = "id",required = false)String id) {
        String token = jwtUtil.getSystemToken();
        if(id==null) {
            id = JWTUtil.getUserId(token);
        }
        //查询公海数据，准备拉取
        JsPublicUsers publicUsers = new JsPublicUsers();
        //publicUsers.setType(0);
        publicUsers.setLimit(20);
        //查询公海20条记录
        List<JsPublicUsers> list2 = jsPublicUsersService.page1(publicUsers);

        //查询私海数据，准备回退
        JsPublicUsersRecord jsPublicUsersRecord = new JsPublicUsersRecord();
        jsPublicUsersRecord.setUserId(Integer.parseInt(id));
        jsPublicUsersRecord.setState(1);
        List<JsPublicUsersRecord> list = jsPublicUsersRecordService.list1(jsPublicUsersRecord);

        //查询现有私海 并 退回到公海
        List<JsPublicUsers> list3 = new ArrayList<>();
        for (JsPublicUsersRecord jsPublicUsersRecord2 : list) {
            jsPublicUsersRecord2.setState(0);

            JsPublicUsers jsPublicUsers = new JsPublicUsers();
            jsPublicUsers.setId(jsPublicUsersRecord2.getPublicUsersId());
            //jsPublicUsers.setType(0);
            list3.add(jsPublicUsers);
        }
        jsPublicUsersService.updateBatchById(list3);
        jsPublicUsersRecordService.updateBatchById(list);

        //更新公海状态并添加至私海
        for (JsPublicUsers jsPublicUsers : list2) {
            //更新公海状态
            jsPublicUsers.setType(-1);
            jsPublicUsers.setUts(new Date());

            //添加到私海
            JsPublicUsersRecord record = new JsPublicUsersRecord();
            record.setPublicUsersId(jsPublicUsers.getId());
            record.setUserId(Integer.parseInt(id));
            record.setCts(new Date());
            record.setState(1);
            jsPublicUsersRecordService.save(record);

        }
        jsPublicUsersService.updateBatchById(list2);

        ArrayList<JsPublicUsers> arrayList = new ArrayList<JsPublicUsers>();

        return R.ok().put("data", arrayList);
    }*/

    //查询我的客户
    @PostMapping("/view")
    public R viewPublicUser(HttpServletRequest request, @RequestBody JsPublicUsers jsPublicUsers) {
        String token = request.getHeader("token");
        Integer userId = Integer.valueOf(JWTUtil.getUserId(token));
        QueryWrapper<JsPublicUsersRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.in("state", 0, 1, 2);
        List<JsPublicUsersRecord> list = jsPublicUsersRecordService.list(queryWrapper);
        if (list.size() <= 0) {
            return R.ok("没有客户信息");
        }
        List<Integer> ids = new ArrayList<>();
        for (JsPublicUsersRecord jsPublicUsersRecord : list) {
            ids.add(jsPublicUsersRecord.getPublicUsersId());
        }
        QueryWrapper<JsPublicUsers> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("id", ids);
        if (jsPublicUsers.getTelephone() != null) {
            queryWrapper1.like("telephone", jsPublicUsers.getTelephone());
        }
        if (jsPublicUsers.getState() != null) {
            queryWrapper1.eq("state", jsPublicUsers.getState());
        }
        IPage<JsPublicUsers> page = new Page<>(jsPublicUsers.getPage(), jsPublicUsers.getLimit());

        IPage<JsPublicUsers> jsPublicUsersIPage = jsPublicUsersService.selectPage(page, queryWrapper1);
        List<JsPublicUsers> records = jsPublicUsersIPage.getRecords();
        for (JsPublicUsers record : records) {
            if (record.getState() == -2) {
                record.setState(0);
            }
        }
        return R.ok().put("data", jsPublicUsersIPage);
    }

    //添加一个我的客户
    @PostMapping("/create")
    public R createPublicUsre(HttpServletRequest request, @RequestBody JsPublicUsers jsPublicUsers) {
        String token = request.getHeader("token");
        Integer userId = Integer.valueOf(JWTUtil.getUserId(token));
        jsPublicUsers.setState(-2);
        jsPublicUsers.setUts(new Date());
        jsPublicUsers.setCts(new Date());
        jsPublicUsersService.save(jsPublicUsers);
        JsPublicUsersRecord jsPublicUsersRecord = new JsPublicUsersRecord();
        jsPublicUsersRecord.setUts(new Date());
        jsPublicUsersRecord.setUts(new Date());
        jsPublicUsersRecord.setState(0);
        jsPublicUsersRecord.setUserId(jsPublicUsers.getId());
        jsPublicUsersRecord.setPublicUsersId(userId);
        jsPublicUsersRecordService.save(jsPublicUsersRecord);
        return R.ok();
    }

    //修改一个我的客户信息
    @PostMapping("/edit")
    public R editPublicUser(@RequestBody JsPublicUsersRecord jsPublicUsers) {
        jsPublicUsersRecordService.updateById(jsPublicUsers);
        return R.ok();
    }

    /**
     * 拉取客户
     */
    @GetMapping("/pullUser")
    public R pullUser(HttpServletRequest request, @RequestParam(value = "count", defaultValue = "20") Integer count) {
        String token = request.getHeader("token");
        Integer userId = Integer.valueOf(JWTUtil.getUserId(token));


        //根据uid查询是否大于300就直接返回不能添加
        //int countPublicUser = jsPublicUsersRecordService.findCountPublicUser(userId);
        //if(countPublicUser>=300){
        //    return R.error("拉去客户数量达到上限");
        //}
        Object o = redisService.get(token);
        if (o == null) {
            return R.error("未登录");
        }
        JsLoginUser jsLoginUser = (JsLoginUser) o;
        List<JsRole> jsRoles = jsLoginUser.getJsRoles();
        List<Integer> branchs = new ArrayList<>();

        for (JsRole jsRole : jsRoles) {
            int branchId = jsRole.getBranchId();
            if (branchId == 0) {
                branchs.clear();
                break;
            }
            branchs.add(branchId);
        }

        //查询公海20条记录(按照退回时间倒序)，准备拉取
        QueryWrapper<JsPublicUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", 0);
        if (branchs.size() > 0) {
            queryWrapper.in("branch_id", branchs);
        }

        queryWrapper.orderByDesc(" uts,IF(ISNULL(uts),1,0) ");
        IPage<JsPublicUsers> page = new Page<>(0, count);
        IPage<JsPublicUsers> jsPublicUsersIPage = jsPublicUsersService.selectPage(page, queryWrapper);
        List<JsPublicUsers> records = jsPublicUsersIPage.getRecords();
        if (records.size() <= 0) {
            return R.error("公海客户没有客户信息，无法拉取");
        }

        //将查询到的公海客户修改状态并加入到我的客户中
        for (JsPublicUsers record : records) {
            //查询我的客户是否曾经有过该客户
            List<JsPublicUsersRecord> jsPublicUsersRecords =
                    jsPublicUsersRecordService.selectByUserIdAndPublicId(userId, record.getId());
            if (jsPublicUsersRecords.size() != 0) {
                for (JsPublicUsersRecord publicUsersRecord : jsPublicUsersRecords) {
                    publicUsersRecord.setState(0);
                    publicUsersRecord.setUts(new Date());
                    jsPublicUsersRecordService.updateById(publicUsersRecord);
                    JsPublicUsers jsPublicUser1 = new JsPublicUsers();
                    jsPublicUser1.setId(record.getId());
                    jsPublicUser1.setState(-2);
                    jsPublicUsersService.updateById(jsPublicUser1);
                }
            } else {
                JsPublicUsers jsPublicUser1 = new JsPublicUsers();
                jsPublicUser1.setId(record.getId());
                jsPublicUser1.setState(-2);
                jsPublicUsersService.updateById(jsPublicUser1);

                //创建我的客户数据
                JsPublicUsersRecord jsPublicUsersRecord = new JsPublicUsersRecord();
                jsPublicUsersRecord.setUserId(userId);
                jsPublicUsersRecord.setPublicUsersId(jsPublicUser1.getId());
                jsPublicUsersRecord.setState(0);
                Date date = new Date();
                jsPublicUsersRecord.setCts(date);
                jsPublicUsersRecord.setUts(date);

                jsPublicUsersRecordService.save(jsPublicUsersRecord);
            }
        }

        return R.ok();
    }

    //客户退回公海
    @PostMapping("/outPublicUserRecord")
    public R outPublicUserRecord(HttpServletRequest request, @RequestBody List<JsPublicUsersRecord> jsPublicUsersRecords) {
        String token = request.getHeader("token");
        Integer uid = Integer.valueOf(JWTUtil.getUserId(token));
        Date date = new Date();
        JsPublicUsers jsPublicUsers = new JsPublicUsers();
        JsPublicUsersRecord jsPublicUsersRecord1 = new JsPublicUsersRecord();
        for (JsPublicUsersRecord jsPublicUsersRecord : jsPublicUsersRecords) {
            int state = jsPublicUsersRecord.getState();
            jsPublicUsers.setId(jsPublicUsersRecord.getId());
            jsPublicUsers.setUts(date);
            jsPublicUsersRecord1.setId(jsPublicUsersRecord.getId());
            jsPublicUsersRecord1.setUts(date);
            //无意向的退回
            if (state == -1) {
            }
            //待沟通的退回
            if (state == 0 || state == 1) {
                jsPublicUsers.setState(0);
                jsPublicUsersService.updateById(jsPublicUsers);
                jsPublicUsersRecord1.setState(-2);
                jsPublicUsersRecordService.updateUserRecord(uid,jsPublicUsersRecord.getId(), jsPublicUsersRecord1);
            }

            //成交的退回
            if (state == 2) {     }
        }

        return R.ok();
    }

    //修改状态
    @PostMapping("/editStatus")
    public R editStatus(HttpServletRequest request, @RequestBody JsPublicUsersRecord jsPublicUsersRecord) {
        String token = request.getHeader("token");
        Integer uid = Integer.valueOf(JWTUtil.getUserId(token));
        Integer state = jsPublicUsersRecord.getState();
        Integer id = jsPublicUsersRecord.getId();
        JsPublicUsers jsPublicUsers = new JsPublicUsers();
        jsPublicUsers.setState(state);
        jsPublicUsers.setId(id);
        jsPublicUsersService.updateById(jsPublicUsers);

        UpdateWrapper<JsPublicUsersRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("public_users_id", id).eq("user_id", uid);

        jsPublicUsersRecord = new JsPublicUsersRecord();
        jsPublicUsersRecord.setState(state);

        boolean b = jsPublicUsersRecordService.update(jsPublicUsersRecord, updateWrapper);

        if (!b) {
            return R.error("修改失败");
        }
        return R.ok();
    }


    //我的客户导入
    @PostMapping("/mytoExcle")
    public R mytoExcle(HttpServletRequest request, @RequestParam("file") MultipartFile file,
                       @RequestParam("areaId")Integer areaId,
                       @RequestParam("branchId")Integer branchId) throws Exception {
        String token = request.getHeader("token");
        Object o = redisService.get(token);
        if(o==null){
            return R.error("未登录");
        }

        File toFile = MultipartFileToFile.multipartFileToFile(file);
        JsLoginUser jsLoginUser =(JsLoginUser)o;
        String name = jsLoginUser.getName();

        Date date = new Date();
        JsPublicUsersGroupby jsPublicUsersGroupby = new JsPublicUsersGroupby();
        jsPublicUsersGroupby.setBranchId(branchId);
        jsPublicUsersGroupby.setLock(1);
        jsPublicUsersGroupby.setCts(date);
        DateFormat format = new SimpleDateFormat("yyyy年MM月dd日-HH时mm分ss秒");
        String format1 = format.format(date);
        jsPublicUsersGroupby.setName(format1+"-"+name);
        jsPublicUsersGroupbyService.save(jsPublicUsersGroupby);

        Integer grouupId = jsPublicUsersGroupby.getId();


        FileInputStream inputStream = new FileInputStream(toFile);
        List<List<Object>> lists = ImportExcelUtil.getBankListByExcel(inputStream, toFile.getName());


        ArrayList<JsPublicUsers> arrayList = new ArrayList<JsPublicUsers>();
        ArrayList<JsPublicUsers> arrayList1 = new ArrayList<JsPublicUsers>();

        for (int i = 0; i < lists.size(); i++) {

            List list = lists.get(i);
            if (list.size() <= 5) {
                for (int n = list.size(); n <= 5; n++) {
                    list.add(null);
                }
            }
            JsPublicUsers publicUsers = new JsPublicUsers();
            //名称
            if (list.get(0) == null) {
                continue;
            }
            publicUsers.setName(list.get(0).toString());

            //电话
            if (list.get(1) == null) {
                continue;
            }
            String s = list.get(1).toString();
            if (s.length() > 11) {
                publicUsers.setTelephone(s.substring(0, 11));
            } else {
                publicUsers.setTelephone(s);
            }
            //地址
            if (list.get(2) != null) {
                publicUsers.setAddress(list.get(2).toString());
            }
            //备注
            if (list.get(3) != null)
                publicUsers.setRemarks(list.get(3).toString());
            //意向等级
            if (list.get(4) != null) {
            }
            //创建时间
            publicUsers.setCts(new Date());
            //类型
            publicUsers.setState(-2);
            publicUsers.setBranchId(branchId);

            publicUsers.setAreaId(areaId);
            publicUsers.setGroupbyId(grouupId);
            arrayList.add(publicUsers);
            if (arrayList.size() == 200) {
                List<JsPublicUsers> jsPublicUsers = jsPublicUsersService.addList(arrayList);
                arrayList1.addAll(jsPublicUsers);
                arrayList.clear();
            }
        }
        if (arrayList.size() > 0) {
            List<JsPublicUsers> jsPublicUsers = jsPublicUsersService.addList(arrayList);
            arrayList1.addAll(jsPublicUsers);
        }


        QueryWrapper<JsPublicUsersGroupby> queryWrapper = new QueryWrapper<>();

        return R.ok();
    }
}